package cn.josewu;

import org.apache.commons.codec.binary.Base64InputStream;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @program: covid19
 * @description:
 * @author: Mr. Tigger
 * @create 2020-10-11 11:46
 **/
public class JdkApiTest {

    @Test
    public void testGet() throws Exception{

        URL url = new URL("http://www.itcast.cn/?username=xx");
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36");
        urlConnection.setConnectTimeout(30000);
        InputStream in = urlConnection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line;
        String html = "";
        while ((line = reader.readLine())!= null) {
            html += line + "\n";
        }
        System.out.println(html);
        in.close();
        reader.close();
    }

    @Test
    public void testPost()  throws Exception {
        URL url = new URL("http://www.itcast.cn/");

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        urlConnection.setDoOutput(true);
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36");
        urlConnection.setConnectTimeout(30000);
        OutputStream out = urlConnection.getOutputStream();
        out.write("username=xx".getBytes());

        InputStream in = urlConnection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line;
        String html = "";
        while ((line = reader.readLine())!= null) {
            html += line + "\n";
        }
        System.out.println(html);
        in.close();
        reader.close();
    }
}
